package com.sgb.kjwl.view.ui.adapter.self.publish;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.AddGoodsItemEntity;

import java.util.List;

public class SelecteUnitAdapter extends RecyclerView.Adapter<SelecteUnitAdapter.MyViewHolder> {
    //当前上下文对象
    Context context;
    List<AddGoodsItemEntity> datas;
    int currentPosition = 0;

    public SelecteUnitAdapter(Context context){
        this.context = context;
    }

    public void setDatas(List<AddGoodsItemEntity> datas) {
        this.datas = datas;
    }

    @NonNull
    @Override
    public SelecteUnitAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        //实例化得到Item布局文件的View对象
        View v = View.inflate(context, R.layout.item_selecte_unit,null);
        //返回MyViewHolder的对象
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull SelecteUnitAdapter.MyViewHolder myViewHolder, int position) {
        myViewHolder.tvName.setText(datas.get(position).getName());
        if (datas.get(position).getSelecte()){
            myViewHolder.ivSelecte.setVisibility(View.VISIBLE);
        }else {
            myViewHolder.ivSelecte.setVisibility(View.GONE);
        }

        if (mItemClickListener != null){
            myViewHolder.ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemClickListener.onItemClick(position);
                    refreshDatas(position);
                }
            });
        }
    }

    public void refreshDatas(int position){
        datas.get(currentPosition).setSelecte(false);
        datas.get(position).setSelecte(true);
        currentPosition = position;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tvName;
        ImageView ivSelecte;
        RelativeLayout ll;
        public MyViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            ivSelecte = itemView.findViewById(R.id.iv_selecte);
            ll = itemView.findViewById(R.id.ll);
        }
    }

    //点击事件
    private ItemClickListener mItemClickListener ;
    public interface ItemClickListener{
        public void onItemClick(int position) ;
    }
    public void setOnItemClickListener(ItemClickListener itemClickListener){
        this.mItemClickListener = itemClickListener ;

    }
}
